package com.colorful.exceldemo.toolkit.excel;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;

import com.colorful.exceldemo.toolkit.EasyExcelUtil;
import com.colorful.exceldemo.toolkit.ExcelValidation;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kang junjie
 * @date 2022/6/2 15:04
 */
@Data
@AllArgsConstructor
@Component
public class CustomSheetWriteHandler implements SheetWriteHandler {
    private final LinkedHashMap<Integer, ExcelSelectedResolve> selectedMap;

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    }
    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // 区间设置 第一列第一行和第二行的数据。由于第一行是头，所以第一、二行的数据实际上是第二三行
        // 这里可以对cell进行任何操作
        Sheet sheet = writeSheetHolder.getSheet();
        Workbook workbook = sheet.getWorkbook();
        DataValidationHelper helper = sheet.getDataValidationHelper();
        selectedMap.forEach((k, v) -> {
            if (v.getRef() != 0) {
                // 级联关系映射
                Map<String, List<String>> map = selectedMap.get(k).getSourceMap().getMap();
                String ref = EasyExcelUtil.excelColIndexToStr(v.getRef() + 1);
                String index = EasyExcelUtil.excelColIndexToStr(k + 1);
                ExcelValidation.addValidationToSheetV1(workbook, sheet, map, ref, index, v.getFirstRow(), v.getLastRow(), helper);
            }
            if (v.getRef() == 0) {
                // 设置下拉列表的行： 首行，末行，首列，末列
                CellRangeAddressList rangeList = new CellRangeAddressList(v.getFirstRow(), v.getLastRow(), k, k);
                // 设置下拉列表的值
                DataValidationConstraint constraint = helper.createExplicitListConstraint(v.getSource());
                // 设置约束
                DataValidation validation = helper.createValidation(constraint, rangeList);
                // 阻止输入非下拉选项的值
                validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
                validation.setShowErrorBox(true);
                validation.setSuppressDropDownArrow(true);
                validation.createErrorBox("提示", "请选择下拉选项中的内容");
                sheet.addValidationData(validation);
            }
        });

    }



}
